from pymongo import MongoClient
import gridfs
from bson import ObjectId
import gridfs
import os
from datetime import datetime 
from pymongo import MongoClient
from bson.binary import Binary
from flask import jsonify
import io
import base64
import re

# 连接到MongoDB（默认连接到本地运行的MongoDB实例）
client = MongoClient('mongodb://localhost:27017/')

db = client['news']  # 替换为你想要的数据库名称
collection = db['news_detail']  # 替换为你想要的集合名称
fs = gridfs.GridFS(db)
#插入会议
def insertnews(data):
    title = data.form.get('title')
    content = data.form.get('content')
    date = data.form.get('date')
    # 检查是否有文件在请求中
    if 'image' in data.files:
        file = data.files['image']
        
        if file:
            # 读取文件的二进制数据
            binary_data = file.read()
            # 创建 Binary 对象
            b = Binary(binary_data)
            # 创建 GridFS 文件记录
            gridfs_file = {
                '_id': ObjectId(),
                'filename': file.filename,
                'contentType': file.content_type,
                'uploadDate': datetime.utcnow()
            }
            
            # 将文件记录保存到 MongoDB
            # 传递二进制数据作为第一个参数，然后传递元数据
            new_id = str(fs.put(binary_data, **gridfs_file))
        else:
            new_id = None
    else:
        new_id = None

    # 创建会议数据记录
    meeting_data = {
        'title': title,
        'content': content,
        'date': date,
        'image_id': new_id  # 保存 GridFS 文件的 _id
    }

    res=collection.insert_one(meeting_data)
    
    return "00"

def get_data_with_files():
    formatted_recommend_items = []

    # Query all news items
    for news in collection.find():
        match = re.search(r"\b\w{3}\s+\d{1,2}\s+\d{4}", news['date'])
        if match:
            news['date'] = match.group()
        formatted_item = {
            'title': news['title'],
            'summary': news['content'],
            'date': news['date'],
            'author': 'admin',
            'detailPath': 'https://example.com/news/' + str(news['_id']),
        }

        if 'image_id' in news and news['image_id']:
            grid_out = fs.get(ObjectId(news['image_id']))
            image_data = grid_out.read()
            formatted_item['imgPath'] = 'data:image/jpeg;base64,' + base64.b64encode(image_data).decode('utf-8')

        formatted_recommend_items.append(formatted_item)
    formatted_recommend_items.reverse()
    return jsonify(formatted_recommend_items)


